#include "apue.h"
#include <sys/msg.h>

#define KEY_PREFIX "MSG_QUEUE_"
#define ITERATOR_COUNT 5

struct mymesg{
    long mtype;
    char mtext[512];
};

int main(void) {
    int i, id;
    key_t key;
    char pname[MAXLINE];
    struct mymesg msg;

    getcwd(pname, MAXLINE);
    for (i=1; i<=ITERATOR_COUNT; ++i) {
        key= ftok(pname, i);
        if ((id= msgget(key, IPC_CREAT | IPC_EXCL)) < 0) 
            err_sys("msgget error");

        printf("identifier: %d, key: %d\n", id, key);
        if (msgctl(id, IPC_RMID, NULL) < 0)
            err_sys("msgctl error");
    }

    for (i=1; i<=ITERATOR_COUNT; ++i) {
        if ((id= msgget(IPC_PRIVATE, IPC_CREAT)) < 0)
            err_sys("msgget error");

        printf("identifier: %d\n", id);
        msg.mtype= 1;
        sprintf(msg.mtext, "The data %d", i);
        msgsnd(id, &msg, strlen(msg.mtext), 0);
    }

    return 0;
}
